package handler

import (
	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/gin-gonic/gin"
	"goweb/db"
	. "goweb/models"
	"goweb/service"
	"log"
	"net/http"
	"strconv"
)

var OrderService service.OrderService

//初始化，生成单例service
func GenerateOrderService() {
	var orderDb db.OrdeDb
	orderDb.Init()
	OrderService.OrderDb = orderDb
}

//上传文件
func UploadHandler(context *gin.Context) {
	id, err := strconv.Atoi(context.PostForm("id"))

	if err != nil {
		context.JSON(200, gin.H{
			"code":    "400",
			"message": "缺少参数-id",
			"data":    "",
		})
		return
	}

	file, err := context.FormFile("file")

	if err != nil {
		context.JSON(200, gin.H{
			"code":    "400",
			"message": "缺少参数-id",
			"data":    "",
		})
		return
	}

	var fileUrl = "resource/" + file.Filename
	context.SaveUploadedFile(file, fileUrl)

	OrderService.SaveFile(fileUrl, id)

	context.JSON(200, gin.H{
		"message": "保存成功",
		"code":    200,
		"data":    fileUrl,
	})
}

//查询所有
func FindOrdersHandler(context *gin.Context) {
	orders, err := OrderService.FindOrders()

	if err != nil {
		context.JSON(200, gin.H{
			"code":    400,
			"message": "查询失败",
			"data":    err.Error(),
		})
	}

	context.JSON(200, gin.H{
		"code":    200,
		"message": "查询成功",
		"data":    orders,
	})
}

//根据userName模糊查找
func FindOrderByLikeUserName(context *gin.Context) {
	userName := context.Param("userName")

	order, err := OrderService.FindOrderByLikeUserName(userName)

	if err != nil {
		context.JSON(200, gin.H{
			"code":    400,
			"message": "查询失败",
			"data":    err.Error(),
		})
	}

	context.JSON(200, gin.H{
		"code":    200,
		"message": "查询成功",
		"data":    order,
	})
}

//根据创建时间与金额排序查找
func FindOrderOrderByCreatedAtAndAmountHandler(context *gin.Context) {
	orders, err := OrderService.FindOrderOrderByCreatedAtAndAmount()

	if err != nil {
		context.JSON(200, gin.H{
			"code":    400,
			"message": "查询失败",
			"data":    err.Error(),
		})
	}

	context.JSON(200, gin.H{
		"code":    200,
		"message": "查询成功",
		"data":    orders,
	})
}

//下载文件
func DownloadHandler(context *gin.Context) {
	response, err := http.Get("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603687567653&di=3b1c0cb1f442b6fbe438dd39c32084ec&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F70%2F91%2F01300000261284122542917592865.jpg")

	if err != nil || response.StatusCode != http.StatusOK {
		log.Println("wrong")
		context.Status(http.StatusServiceUnavailable)
		return
	}

	extraHeaders := map[string]string{
		"Content-Disposition": `attachment; filename="tiger.jpg"`,
	}

	context.DataFromReader(200, response.ContentLength, response.Header.Get("Content-Type"), response.Body, extraHeaders)
}

//添加订单
func AddOrderHandler(context *gin.Context) {
	var order DemoOrder

	context.ShouldBind(&order)

	err := OrderService.AddOrder(order)

	if err != nil {
		context.JSON(200, gin.H{
			"code":    "400",
			"message": "添加失败,订单已经存在",
			"data":    "",
		})
	} else {
		context.JSON(200, gin.H{
			"code":    "200",
			"message": "添加成功",
			"data":    "",
		})
	}
}

//更新订单
func UpdateOrderHandler(context *gin.Context) {
	id, err := strconv.Atoi(context.PostForm("id"))

	if err != nil {
		context.JSON(200, gin.H{
			"code":    "400",
			"message": "请传数字",
			"data":    "",
		})
		return
	}

	var orderById DemoOrder

	orderById, err = OrderService.FindOrderById(id)

	if err != nil {
		context.JSON(200, gin.H{
			"code":    400,
			"message": "查询失败",
			"data":    err.Error(),
		})
	}

	var order DemoOrder
	context.ShouldBind(&order)

	order.ID = orderById.ID

	err = OrderService.UpdateOrder(order)

	if err != nil {
		context.JSON(200, gin.H{
			"code":    "400",
			"message": "更新失败",
			"data":    "",
		})
	} else {
		context.JSON(200, gin.H{
			"code":    "400",
			"message": "更新成功",
			"data":    order,
		})
	}
}

func XLSXDownloadHandler(context *gin.Context) {
	file := excelize.NewFile()

	file.SetCellValue("sheet1", "A1", "order_no")
	file.SetCellValue("sheet1", "B1", "user_name")
	file.SetCellValue("sheet1", "C1", "amount")
	file.SetCellValue("sheet1", "D1", "status")
	file.SetCellValue("sheet1", "E1", "file_url")

	orders, err := OrderService.FindOrders()

	if err != nil {
		context.JSON(200, gin.H{
			"code":    400,
			"message": "查询失败",
			"data":    err.Error(),
		})
	}

	var i int = 2
	for _, order := range orders {
		file.SetCellValue("sheet1", "A"+strconv.Itoa(i), order.OrderNo)
		log.Println("A" + strconv.Itoa(i))
		file.SetCellValue("sheet1", "B"+strconv.Itoa(i), order.UserName)
		file.SetCellValue("sheet1", "C"+strconv.Itoa(i), order.Amount)
		file.SetCellValue("sheet1", "D"+strconv.Itoa(i), order.Status)
		file.SetCellValue("sheet1", "E"+strconv.Itoa(i), order.FileUrl)

		i++
		log.Println(i)
	}

	context.Header("Content-Type", "application/octet-stream")
	context.Header("Content-Disposition", "attachment; filename="+"orders.xlsx")
	context.Header("Content-Transfer-Encoding", "binary")

	file.Write(context.Writer)
}
